package com.af.system.servlet.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : zhenyun.su
 * @since : 2019/6/10
 * 来源： 3-webmvc/1-restful
 */

public class AfMonitorInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(AfMonitorInterceptor.class);
    
    long start = System.currentTimeMillis();
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o){
        String url=httpServletRequest.getRequestURI();
        logger.debug("af, MonitorInterceptor preHandle, url={}", url);
        start = System.currentTimeMillis();
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        String sessionId="";
        //自定义拦截器中不要创建session，因此参数为false
        if (httpServletRequest.getSession(false) != null){
            sessionId= httpServletRequest.getSession().getId();
        }
        long elapseTime= System.currentTimeMillis()-start;
        logger.debug("af, MonitorInterceptor postHandle, finish, session Id: {}, consumed : {} millisecond", sessionId, elapseTime);
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.debug("af, MonitorInterceptor afterCompletion, finish, Object: {} ; exception: {}", o, e);
    }
}
